/*
 * @Description: 路由守卫
 * @Author: wangqi
 * @Date: 2022-04-21 16:41:58
 * @LastEditTime: 2022-04-21 18:14:29
 */
import NProgress from 'nprogress'; // progress bar
import { type Router, isNavigationFailure } from 'vue-router';
import { message } from 'ant-design-vue';

import { type WhiteNameList, LOGIN_NAME } from './constant';
import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum';
import { useUserStore } from '@/store/modules/user';
import { Storage } from '@/utils/Storage';

NProgress.configure({ showSpinner: false });
const defaultRoutePath = '/dashboard/index';
export function createRouterGuards(router: Router, whiteNameList: WhiteNameList) {
  router.beforeEach(async (to, from, next) => {
    console.log(typeof from, 'beforeEach');

    const userStore = useUserStore();
    NProgress.start();
    const token = Storage.get(ACCESS_TOKEN_KEY);
    if (token) {
      if (to.name === LOGIN_NAME) {
        next({ path: defaultRoutePath });
        NProgress.done();
      } else {
        const hasRoute = router.hasRoute(to.name!);
        if (userStore.menus.length === 0) {
          // 从后端获取菜单
          await userStore.afterLogin();

          if (!hasRoute) {
            // TODO 未完成, 需参考
            next({ ...to, replace: true });
          }

          if (whiteNameList.some((val) => val === to.name) || hasRoute) {
            //  白名单免登录, 直接进入
            next();
          }
        } else {
          next();
        }
      }
    } else {
      // 全回到登录页 | 白名单配置页
      if (whiteNameList.some((val) => val === to.name)) {
        // 进入白名单配置页
        next();
      } else {
        next({ name: LOGIN_NAME, query: { redirect: to.fullPath }, replace: true });
        NProgress.done();
      }
    }
  });

  router.afterEach((to, _, failure) => {
    console.log(typeof to, '|-afterEach');

    if (isNavigationFailure(failure)) {
      message.error('This is a normal message');
    }

    NProgress.done();
  });

  router.onError((error) => {
    console.log(error, '路由错误');
  });
}
